﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class MainForm
    {
        /* This part of the class contains methods that assign event handlers
         * both to UI objects (WinForm controls) and custom objects used by the application.
         * 
         * I avoided */
        /// <summary>
        /// All actions necessary When the form gets loaded.
        /// </summary>
        /// <remarks>
        /// This method is called by the Load event
        /// </remarks>
        private void StartUp()
        {
            rbShowOnlySomeonesRequests.Tag = rbShowOnlySomeonesRequests.Text;
            IconTabs();
            Set_sheetHolidayEmployeesColumns();

            Program.CurrentTheme = new Theme();

            Size = new Size(1080, 780);
            CenterToScreen();
            ROTA_SetEventHandlers();
            
            SQLiteAccess.OnDataChanged += SQLiteAccess_OnDataChanged;
            REQUESTS_BindControls();
            DataBind_lvHolidays();
            if (!PromptAndLoadFiles(
                new OpenFileFormMode(
                OpenFileMode.CreateOrOpen,
                OpenFileMode.CreateOrOpen)))
            {                
                Program.Quit();                
                Environment.Exit(0);
            }
            HOLIDAYS_SetEventHandlers();
            
            
            Program.CurrentFile.Modified = false;
            SetAndAssignGroups();

            #region hide



            ctrlsToHideOnPanel2 = new Control[]
                                      {
                                          tblTempToolbar,
                                          svTemplate,
                                          sheetTempOpeningHrs
                                      };

            SaveSplitterPanelPosition();

            lastUsed = Generator.Parameters.GetDefaultParameters();
            lastUsedAddEmpToTemp = -1;


            #endregion

            svRota.RightSidePreferred = true;
            svRota.BottomPreferred = true;
            svTemplate.RightSidePreferred = true;
            svTemplate.BottomPreferred = true;
            sheetTempOpeningHrs.RightSidePreferred = true;
            sheetTempOpeningHrs.BottomPreferred = true;

            layoutAdjustWholeUI();

            btnPrev.Click += btnPrev_Click;
            btnNext.Click += btnNext_Click;


            btnSaveRota.Click += btnSaveRota_Click;
            
            btnNewTemplate.Click += btnNewTemplate_Click;
            btnSaveTemplate.Click += btnSaveTemplate_Click;
            btnDeleteTemplate.Click += btnDeleteTemplate_Click;

            btnGenerate.Click += (sender, e) => Generate();
            MENUBAR_SetEventHandlers();
            PopulateMRUInMainMenu();
            Program.MRURotasFiles.OnListUpdated += MRURotasFiles_OnListUpdated;
            DisableUnaccessibleUIControls();
            STAFF_SetEventHandlers();
            REQUESTS_SetEventHandlers();
            CALENDAR_SetEventHandlers();
            UpdateTitlebar();
            cbTemplate.SelectedValueChanged += cbTemplate_SelectedValueChanged;
            cbTemplate.Enter += cbTemplate_Enter;
        }

        void MRURotasFiles_OnListUpdated()
        {
            PopulateMRUInMainMenu();
        }

        private void HOLIDAYS_SetEventHandlers()
        {
            SQLiteAccess.OnHolidayYearSpanChanged += cbYear_Refresh;       
            cbShowFinished.CheckedChanged += (sender, e) => lvHolidays_Populate();
            cbShowPending.CheckedChanged += (sender, e) => lvHolidays_Populate();
            cbShowAll.CheckedChanged += (sender, e) => lvHolidays_Populate();
            dgridHolidayEmployees.SelectionChanged += (sender, e) =>
                                                          {
                                                              if (cbShowAll.Checked)
                                                              {
                                                                  return;
                                                              }
                                                              if (dgridHolidayEmployees.SelectedRows.Count > 0)
                                                              {
                                                                  lvHolidays_Populate();
                                                              }
                                                          };
            btnAddHolidays.Click += btnAddHolidays_Click;
            btnAddPendingHolidays.Click += btnAddPendingHoliday_Click;
            btnEditHolidays.Click += btnEditHolidays_Click;
            btnEditPendingHolidays.Click += btnEditPendingHolidays_Click;
            btnAcceptPendingHolidays.Click += btnAcceptPendingHolidays_Click;
            btnRejectPendingHolidays.Click += btnRejectPendingHolidays_Click;
            btnDeleteHolidays.Click += btnDeleteHolidays_Click;
            cbHolidaysGroupBy_Initialize();
        }

        private void CALENDAR_SetEventHandlers()
        {
            sheetCalendar.CellClick +=
                sheetCalendar_CellClick;
            sheetCalendar.CellFormatting +=
                sheetCalendar_CellFormatting;


            cbHideArchiveOnes.CheckedChanged += cbHideArchiveOnes_CheckedChanged;
            cbWeek.SelectedIndexChanged += cbWeek_SelectedIndexChanged;
            btnCurrentWeek.Click += (sender, e) => PerformAction(
                Program.CurrentFile.CurrentRota,
                Program.CurrentFile.CurrentRota.ProperAction);
            btnNextWeek.Click += (sender, e) => PerformAction(
                Program.CurrentFile.NextRota,
                Program.CurrentFile.NextRota.ProperAction);
        }

        public void MENUBAR_SetEventHandlers()
        {
            miFileNew.Click += FileNew_Click;
            miHelpAbout.Click += HelpAbout_Click;
            miExit.Click += Exit_Click;
            miFileOpen.Click += openToolStripMenuItem_Click;
            miFileSave.Click += saveToolStripMenuItem_Click;
            miFileSaveAs.Click += saveasToolStripMenuItem_Click;
            miFileImportTemplates.Click += miFileImportTemplates_Click;
            miUserAccount.Click += userAccountToolStripMenuItem_Click;
            miOptionsPlaySounds.Checked = Program.PlaySounds;
            miOptionsPlaySounds.Click += playsoundsToolStripMenuItem_Click;
            miLogin.Click += logOutToolStripMenuItem_Click;
            miCreateNewSQLDb.Click += createnewToolStripMenuItem_Click;
            miOpenAnotherSQL.Click += openAnotherToolStripMenuItem_Click;
        }

        private void STAFF_SetEventHandlers()
        {
            btnManageHolidays.Click += btnManageHolidays_Click;
            btnChangeContract.Click+=btnChangeContract_Click;
        }

        private void STAFF_InitializeFilterComboBoxes()
        {            
            var contractStatus = new List<KeyValuePair<string,string>>
                                     {
                                         new KeyValuePair<string, string>(
                                             Resources.FORM_MAINFORM_CONTRACTSTATUSFILTER_EmployedNow_TEXTVALUE,
                                             Resources.FORM_MAINFORM_CONTRACTSTATUSFILTER_EmployedNow_ROWFILTEREXPRESSION),
                                         new KeyValuePair<string, string>(
                                             Resources.FORM_MAINFORM_CONTRACTSTATUSFILTER_WorkingNow_TEXTVALUE,
                                             Resources.FORM_MAINFORM_CONTRACTSTATUSFILTER_WorkingNow_ROWFILTEREXPRESSION),
                                         new KeyValuePair<string, string>(
                                             Resources.FORM_MAINFORM_CONTRACTSTATUSFILTER_NoFilter_TEXTVALUE,
                                             String.Empty)
                                     };


            
            foreach (var cb in new[] { cbJobTitleStatus, cbContractStatusFilter })
            {
                cb.DisplayMember = "Key";
                cb.ValueMember = "Value";
                cb.SelectedValueChanged += (sender, e) =>
                                               {
                                                   if (cbContractStatusFilter.SelectedValue == null ||
                                                       cbJobTitleStatus.SelectedValue == null)
                                                   {
                                                       /* it means that datasource for one of the comboboxes
                                                        * is not yet set. it used to cause an exception after
                                                        * setting this datasource for the first, while the other
                                                        * one still had no values */
                                                       return;
                                                   }
                                                   var f1 = cbContractStatusFilter.SelectedValue.ToString();
                                                   var f2 = cbJobTitleStatus.SelectedValue.ToString();
                                                   // we use AND only if we have two criteria, so that there'pShift one On each side of AND
                                                   var rowFilter = f1 +
                                                                   ((f1 == String.Empty || f2 == String.Empty)
                                                                        ? String.Empty
                                                                        : " AND ") + f2;

                                                   if (rowFilter == SQLiteAccess.EmployeesForStaffTab.RowFilter)
                                                   {
                                                       return;
                                                   }
                                                   SQLiteAccess.SetFilterForStaffOnStaffTab(rowFilter);
                                                   reload_lbStaffMembers();
                                                   STAFF_BindDetailsControls();
                                               };
            }
            cbContractStatusFilter.DataSource = contractStatus;
            cbJobTitleStatus.DataSource = GetJobTitlesDataSource;
            cbPositionsEmployeesRequest.DataSource = GetJobTitlesDataSource;

        }

        private void REQUESTS_SetEventHandlers()
        {
            btnAddRequest.Click +=
                btnAddRequest_Click;
            btnAddPendingRequest.Click +=
                btnAddPendingRequest_Click;
            btnEditRequest.Click +=
                btnEditRequest_Click;
            btnEditPendingRequest.Click +=
                btnEditPendingRequest_Click;
            btnAcceptPendingRequest.Click += btnAcceptPendingRequest_Click;
            btnRejectPendingRequest.Click += btnRejectPendingRequest_Click;
            btnDeleteRequest.Click += btnDeleteRequest_Click;
            cbPositionsEmployeesRequest.SelectedValueChanged += cbPositionEmployeesRequest;
            lbEmployeesRequests.SelectedValueChanged += lbEmployeesRequests_SelectedValueChanged;
            cbRequestsJustCurrentEmployees.CheckedChanged += cbRequestsJustCurrentEmployees_CheckedChanged;
            dgridRequests.SelectionChanged += dgridRequests_SelectionChanged;
            dgridRequestsPending.SelectionChanged += dgridRequestsPending_SelectionChanged;
            
            foreach (var checkbox in new[]
                                         {
                                             cbIncludePassedRequests,
                                             cbIncludePendingRequests
                                         })
            {
                checkbox.CheckedChanged += (sender, e) => dgridRequests_Populate();
            }
            foreach (var radiobutton in new[]
                                            {
                                                rbShowEverybodysRequests,
                                                rbShowOnlySomeonesRequests
                                            })
            {
                radiobutton.CheckedChanged += (sender, e) => dgridRequests_Populate();
            }
        }

        private void ROTA_SetEventHandlers()
        {
            svRota.OnRefreshTotalHours += sheetRota_OnRefreshTotalHours;
            svRota.OnCellEntered += sheetRota_OnCellEntered;
            svRota.OnMustRecalculateDiscrepancies += OnMustRecalculateDiscrepancies;
            svTemplate.OnMustRecalculateDiscrepancies += OnMustRecalculateDiscrepancies;
            tbCellNotesOrHoliday.MouseDown += tbCellNotesOrHoliday_MouseDown;

            btnNotes.Click += (sender, e) =>
                                  {
                                      if (svRota.SelectedCells.Count == 0)
                                      {
                                          return;
                                      }
                                      svRota.AddNotes(
                                          svRota.SelectedCells[0].ColumnIndex,
                                          svRota.SelectedCells[0].RowIndex);
                                  };
            

            
            #region context menus
            svRota.CellMouseDown += PopupMenuEntry.ShowContextMenu;
            svTemplate.CellMouseDown += PopupMenuEntry.ShowContextMenu;
            #endregion
        }

        private void CURRENTFILE_SetEventHandlers()
        {
            Program.CurrentFile.OnRotasCollectionModified +=
                CurrentFile_OnRotasCollectionModified;
            Program.CurrentFile.OnTemplatesCollectionModified +=
                CurrentFile_OnTemplatesCollectionModified;
            CurrentFile_OnRotasCollectionModified();
            CurrentFile_OnTemplatesCollectionModified();
        }
    }
}
